<?php

include (APPPATH.'/models/model.php');

class Viability extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->model('viability_model');
	}

	public function index()
	{
		$this->load->helper('form');
		$this->load->library('form_validation');

		$this->load->view('templates/header');

		$characteristics = $this->viability_model->get_characteristics();
		$items = array();
		foreach ($characteristics as $c){			
			array_push($items, new Characteristic($c['id'], 
			$c['denominacion'], 
			$c['categoria'],
			$c['peso'],
			$c['esencial'],
			$c['naturaleza'],
			$c['umbral'],
			$c['dimension']));
		}

		$data['characteristics'] = $items;
		$this->load->view('viability/index', $data);

		$this->load->view('templates/footer');
	}

	public function evaluate(){
		$errors = array();
		$sets = array();
		$chars = array();
		$characteristics = $this->viability_model->get_characteristics();		
		for ($i = 1; $i <= count($characteristics); $i++) {
			$answer = $this->input->post(strval($i), TRUE);

			if ($answer == null){
				array_push($errors, "No dio respuesta para la pregunta ". $i."</br>");
				continue;
			}
			$c = $characteristics[$i-1];
			$char = new Characteristic($c['id'], 
			$c['denominacion'], 
			$c['categoria'],
			$c['peso'],
			$c['esencial'],
			$c['naturaleza'],
			$c['umbral'],
			$c['dimension']);

			if ($char->threshold->causesError($answer)){
				array_push($errors, $char->threshold->getError($answer));
				continue;
			}
			$set = FuzzySet::create($c['peso'],$c['naturaleza'], $answer);
			array_push($sets, $set);
			array_push($chars, $char);
		}

		$dimensionWeightSums = array(0,0,0,0);
		$dimensionProductSums = array(FuzzySet::no(),FuzzySet::no(),FuzzySet::no(),FuzzySet::no());
		$globals = array();

		if (count($errors) == 0){
			for ($i = 0; $i < count($sets); $i++) {
				$c = $chars[$i];
				$set = $sets[$i];
				$dimensionWeightSums[$c->dimension - 1] += abs($c->weight);
				$currentProduct = $dimensionProductSums[$c->dimension - 1];
				$newProduct = $currentProduct->add($set->multiply(abs($c->weight)));
				$dimensionProductSums[$c->dimension - 1] = $newProduct;
				// missing inverse for fuzzyrange
			}

			$fuzzySum = FuzzySet::no();
			$weightSum = 0;

			for ($i = 0; $i < 4; $i++) {
				$global = $dimensionProductSums[$i]->divide($dimensionWeightSums[$i]);
				array_push($globals, $global);
				$weight = Characteristic::getWeightForDimension($i + 1);
				$weightSum += $weight;
				$fuzzySum = $fuzzySum->add($global->multiply($weight));
			}
			
			$final = $fuzzySum->divide($weightSum);
			$data['final'] = $final;
		}

		$data['errors'] = $errors;
	
		$this->load->view('templates/header');
		$this->load->view('viability/result', $data);
		$this->load->view('templates/footer');
	}
}
?>

